package com.xinnet.mms.web;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSON;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.allot.dao.CustomAllotDao;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.config.service.FlowTurnConfigService;
import com.xinnet.mms.customerConsumeManage.service.CustomerConsumeManageService;
import com.xinnet.mms.customerManage.service.CustomerManageService;
import com.xinnet.mms.customerstate.service.CustomerStateHistService;
import com.xinnet.mms.dept.service.DeptService;
import com.xinnet.mms.deptarea.service.DeptAreaService;
import com.xinnet.mms.empcustomrelation.service.EmpCustomRelationService;
import com.xinnet.mms.entity.AllotStatus;
import com.xinnet.mms.entity.CustomStateHist;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.CustomerConsume;
import com.xinnet.mms.entity.CustomerRemark;
import com.xinnet.mms.entity.Dept;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.entity.Role;
import com.xinnet.mms.entity.ScanningList;
import com.xinnet.mms.enums.CustomerTypeEnmu;
import com.xinnet.mms.login.service.EmpService;
import com.xinnet.mms.member.service.MemberService;
import com.xinnet.mms.order.service.OrderService;
import com.xinnet.mms.utils.CustomerManage;
import com.xinnet.mms.utils.JsonUtil;

/**
 * 
 * 类描述：客户管理 -- 用于各种对客户操作的类
 * 
 * @author 李丽华[lilihua@xinnet.com]
 * 
 * @version 1.0
 * 
 * @since 2014-1-15
 */
@Controller
@RequestMapping(value = "/customerManage")
public class CustomerManageController {

	@Autowired
	private CustomerManageService customerManageService;
	
	@Autowired
	private CustomerConsumeManageService customerConsumeManageService;

	@Autowired
	private CustomAllotService customAllotService;

	@Autowired
	private DeptService deptService;

	@Autowired
	private EmpCustomRelationService empCustomRelationService;

	@Autowired
	private CustomerStateHistService customerStateHistService;

	@Autowired
	private EmpService empService;
	
	@Autowired
	private MemberService memberService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private DeptAreaService deptAreaService;

	@Autowired
	FlowTurnConfigService flowTurnConfigService;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	ObjectMapper mapper = new ObjectMapper();
	private static Log log = LogFactory.getLog(CustomerManageController.class);
	/**
	 * 
	 * 方法描述：查询客户
	 * 
	 * 
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-1-16 下午3:44:29
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryCustomer")
	public void queryCustomer(Customer customer, PageView<Customer> page,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}
		log.info(currentUser.getEname()+"正在查看客户，sessionID:"+session.getId());
		String s = request.getRequestURL().toString();
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible() && currentUser.getIsResponsible().equals(CustomerManage.IS_RESPONSIBLE_YES) && (null == customer.getEmpno() || "".equals(customer.getEmpno()))) {
			if (null == customer.getDeptId() || "".equals(customer.getDeptId())) {
				customer.setDeptId(currentUser.getId());
			}
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}
		
		String nolinkedDay1 = customer.getNolinkedDay1();
		String nolinkedDay2 = customer.getNolinkedDay2();
		if(nolinkedDay1!=null&&!"".equals(nolinkedDay1)&&nolinkedDay2!=null&&!"".equals(nolinkedDay2)){
			
			Calendar c1 = Calendar.getInstance();
			c1.setTime(new Date());
			int int1 = -Integer.valueOf(nolinkedDay1);
			int int2 = -Integer.valueOf(nolinkedDay2);
			c1.add(Calendar.DATE,int1);
			
			Calendar c2 = Calendar.getInstance();
			c2.setTime(new Date());
			c2.add(Calendar.DATE,int2);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			nolinkedDay1 = sdf.format(c1.getTime());
			nolinkedDay2 = sdf.format(c2.getTime());
			customer.setNolinkedDay1(nolinkedDay1+" 23:59:59");
			customer.setNolinkedDay2(nolinkedDay2+" 00:00:00");
		}

		customer.setIsDebug(ConfigUtil.getString("isTest"));
		if("--".equals(customer.getCustomId())){
			if (!role.getName().equals("总经理") && !role.getName().equals("副总经理") && role.getName().indexOf("总监")<0) {
				customer.setCustomId("");
				Calendar cal = Calendar.getInstance(); 
				cal.setTime(new Date());
				cal.add(Calendar.DATE, -1);
				customer.setStartAddTime(sdf.format(cal.getTime()));
				customer.setEndAddTime(sdf.format(new Date()));
			}
		}
		PageView<Customer> pageView =  null;
		if("--".equals(customer.getCustomId())){
			pageView = new  PageView<Customer>();
			pageView.setRecords(new ArrayList<Customer>());
		} else {
			pageView = customerManageService.queryCustomer(page,
					customer);
		}

		List<Customer> customerList = null;
		// 获取分页List
		if (null != pageView) {
			customerList = pageView.getRecords();
		}
		
		//判断权限
		Subject subject = SecurityUtils.getSubject();
		if(subject.isPermitted("客户调配") ){
			 map.put("isHasCustomAllot", "0");
		} else {
			map.put("isHasCustomAllot", "1");
		}
		if(customer.getCustomId()!=null || "--".equals(customer.getCustomId())){
			customer.setCustomId("");
		}
		map.put("custom", customer);
		String customerListStr = mapper.writeValueAsString(customerList);
		pw.println(customerListStr);

	}
	
	/**
	 * 
	 * 方法描述：查询客户，该查询不分
	 * 
	 * 
	 * 
	 * @author 王志军
	 * 
	 *         2016-9-9 下午5:44:29
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/queryCustomerNew")
	public void queryCustomerNew(Customer customer, PageView<Customer> page,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map,Model model) throws Exception {
		PrintWriter pw = response.getWriter();
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}
		log.info(currentUser.getEname()+"正在查看客户，sessionID:"+session.getId());
		String s = request.getRequestURL().toString();
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible() && currentUser.getIsResponsible().equals(CustomerManage.IS_RESPONSIBLE_YES) && (null == customer.getEmpno() || "".equals(customer.getEmpno()))) {
			if (null == customer.getDeptId() || "".equals(customer.getDeptId())) {
				customer.setDeptId(currentUser.getId());
			}
		}
		//临时写到后台的时间处理方法，可以改写前端页面直接传入 startAddTime和endAddTime
		String operateTime = customer.getOperateTime();
		if(operateTime!=null&&operateTime!=""){
			customer.setStartAddTime(operateTime.split(" ")[0]);
			customer.setEndAddTime(operateTime.split(" ")[2]);
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}
		customer.setIsDebug(ConfigUtil.getString("isTest"));
		Integer rows = Integer.valueOf(request.getParameter("rows"));
		page.setPageNow(Integer.valueOf(request.getParameter("page")));
		customer.setLimitTop(page.getFirstResult());
		customer.setLimitDown(rows);
		
		List<Customer> customerList = customerManageService.queryCustomer(customer);
		
		
		int totalCount = customer.getRowCount();
		Integer pageCount = (totalCount + rows - 1) / rows;
		page.setRowCount(totalCount);
		page.setPageCount(pageCount);
		page.setRecords(customerList);
	    String str1 = mapper.writeValueAsString(page);
	    if(customer.getCustomId() != null && "--".equals(customer.getCustomId())){
	    	customer.setCustomId(null);
	    }
//	    model.addAttribute("customer",customer);
	    session.setAttribute("customer", customer);
		pw.print(str1);

	}
	

	/**
	 * 
	 * 方法描述：全部调配查询
	 * 
	 * 
	 * 
	 * @author 邢泽江
	 * 
	 *         2016年11月23日11:01:21
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/queryCustomerNumber")
	public void queryCustomerNumber(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		AllotStatus reusult = new AllotStatus();
		int resultNum = 0;
		PrintWriter pw = response.getWriter();
		System.out.println(request.getCharacterEncoding());

		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}
		log.info(currentUser.getEname()+"正在查看客户，sessionID:"+session.getId());
		String s = request.getRequestURL().toString();
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible() && currentUser.getIsResponsible().equals(CustomerManage.IS_RESPONSIBLE_YES) && (null == customer.getEmpno() || "".equals(customer.getEmpno()))) {
			if (null == customer.getDeptId() || "".equals(customer.getDeptId())) {
				customer.setDeptId(currentUser.getId());
			}
		}
		//临时写到后台的时间处理方法，可以改写前端页面直接传入 startAddTime和endAddTime
		String operateTime = customer.getOperateTime();
		if(operateTime!=null&&operateTime!=""){
			customer.setStartAddTime(operateTime.split(" ")[0]);
			customer.setEndAddTime(operateTime.split(" ")[2]);
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}
		
		//调配数量超过2000，则数量过多，返回状态1
		resultNum = customerManageService.getCustomerCount(customer);
		if(resultNum==0||resultNum>2000){
			reusult.setStatus("1");
			String str1 = mapper.writeValueAsString(reusult);
			pw.print(str1);
			return;
		}
//		customer.setIsDebug(ConfigUtil.getString("isTest"));
		customer.setLimitTop(0);
		customer.setLimitDown(resultNum);
		List<Customer> customerList = customerManageService.queryCustomer(customer);
		
		//打包customerid
		String[] customerIds = new String[customerList.size()];
		for(int i=0;i<customerList.size();i++){
			customerIds[i] = customerList.get(i).getCustomId();
		}		
		//如果只有一条，直接返回
		if(resultNum==1){
			reusult.setStatus("0");
			reusult.setCurrentCustomer(customerList.get(0));
			reusult.setCustomerIds(this.toString(customerIds));
			String str1 = mapper.writeValueAsString(reusult);
			pw.print(str1);
			return;
		}
		//调配数据不属于同一分公司，返回状态2
		String firstCompanyAbb = customerList.get(0).getCompanyAbb();
		for(Customer c : customerList){
			if(!firstCompanyAbb.equals(c.getCompanyAbb())){
				reusult.setStatus("2");
				String str1 = mapper.writeValueAsString(reusult);
				pw.print(str1);
				return;
			}
		}
		
		
		//大于2条数据，且属于同一分公司，数量小于2000，打包数据
		reusult.setStatus("0");
		reusult.setCurrentCustomer(customerList.get(0));
		reusult.setCustomerIds(this.toString(customerIds));
		String str1 = mapper.writeValueAsString(reusult);
		pw.print(str1);

	}

	/**
	 * 
	 * 方法描述：查询公海客户
	 * 
	 * 
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-1-16 下午3:44:29
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryOpenSeeCustomer")
	public void queryOpenSeeCustomer(Customer customer,
			PageView<Customer> page, HttpServletRequest request,
			HttpServletResponse response, HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();

		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}
		
		customer.setDeptId(currentUser.getId());
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}
		PageView<Customer> pageView = new PageView<Customer>();
		customer.setIsDebug(ConfigUtil.getString("isTest"));
		String nolinkedDay1 = customer.getNolinkedDay1();
		String nolinkedDay2 = customer.getNolinkedDay2();
		if(nolinkedDay1!=null&&!"".equals(nolinkedDay1)&&nolinkedDay2!=null&&!"".equals(nolinkedDay2)){
			
			Calendar c1 = Calendar.getInstance();
			c1.setTime(new Date());
			int int1 = -Integer.valueOf(nolinkedDay1);
			int int2 = -Integer.valueOf(nolinkedDay2);
			c1.add(Calendar.DATE,int1);
			
			Calendar c2 = Calendar.getInstance();
			c2.setTime(new Date());
			c2.add(Calendar.DATE,int2);
			
			nolinkedDay1 = sdf.format(c1.getTime());
			nolinkedDay2 = sdf.format(c2.getTime());
			customer.setNolinkedDay1(nolinkedDay1);
			customer.setNolinkedDay2(nolinkedDay2);
		}
		
		if(currentUser.getIsResponsible()==0){
			pageView.setRecords(new ArrayList<Customer>());
		} else {
			if("--".equals(customer.getCustomId())){
				if (!role.getName().equals("总经理") && !role.getName().equals("副总经理") && role.getName().indexOf("总监")<0) {
					customer.setCustomId("");
					/*Calendar cal = Calendar.getInstance(); 
					cal.setTime(new Date());
					cal.add(Calendar.DATE, -1);
					customer.setStartAddTime(sdf.format(cal.getTime()));
					customer.setEndAddTime(sdf.format(new Date()));*/
				}
			}
			if("--".equals(customer.getCustomId())){
				pageView.setRecords(new ArrayList<Customer>());
			} else {
				List<String> aa =new ArrayList<String>();
				 for (String temp : customer.getAreaIdList()) {
					if(temp!=null && temp.length()>0){
						 aa.add(temp);
					} 
				}
				 customer.setAreaIdList(aa);
				pageView = customerManageService.queryOpenSeeCustomer(page, customer);
				
			}
		}
		if(customer.getCustomId()!=null || "--".equals(customer.getCustomId())){
			customer.setCustomId("");
		}

		List<Customer> customerList = null;
		// 获取分页List
		if (null != pageView) {
			customerList = pageView.getRecords();
		}
		//判断权限
		Subject subject = SecurityUtils.getSubject();
		if(subject.isPermitted("客户调配") ){
			 map.put("isHasCustomAllot", "0");
		} else {
			map.put("isHasCustomAllot", "1");
		}
		String customerListStr = mapper.writeValueAsString(customerList);
		System.out.println(JsonUtil.toJson(customerList));
		pw.println(customerListStr);

	}

	/**
	 * 
	 * 方法描述：接收客户
	 * 
	 * @return
	 * 
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-1-16 下午3:45:07
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/acceptCustomer")
	public void accept(Customer customer, HttpSession session,
			HttpServletResponse response) throws Exception {
		PrintWriter pw = response.getWriter();

		if (null != customer) {
			String[] ecrIdArray = customer.getEcrIdStr().split(":");
			String[] cusIdArray = customer.getCusIdStr().split(":");
			String[] empIdArray = customer.getEmpIdStr().split(":");
			String[] productIdArray = customer.getProductIdStr().split(":");

			// 判断要接收的客户是否还在
			int length = ecrIdArray.length;
			for (int i = 0; i < length; i++) {
				Integer result = checkCustomerIsExist(ecrIdArray[i],
						CustomerManage.ACCEPT);
				if (result != 1) {
					pw.println(result);
					return;
				}
			}

			EmpCustomRelation empCustomRelation = new EmpCustomRelation();
			for (int i = 0; i < ecrIdArray.length; i++) {
				// 1、将客户销售关系表中该条信息客户状态改为已接收&添加流走时间
				empCustomRelation.setId(ecrIdArray[i]);
				// 设置状态为接收
				empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
				// 查询客户在销售手里的保留期(分为 系统推送/人工推送保留期 只有意向客户才会查找人工推送保留期)

				Product product = customerManageService
						.getProductByProductId(productIdArray[i]);
				if(product==null){
					product = customAllotService.getDefaultProduct();
				}
				Integer holdTime = null;// 保留天数
				Integer pushNodealholdtime = product.getPushNodealholdtime();// 人工推送保留期
				Integer sysallocationNodealholdtime = product
						.getSysallocationNodealholdtime();// 系统推送保留期

				Integer middleServiceCycle = product.getMiddleServiceCycle();// 二次开发停顿期
				Integer redevNodealholdtime = product.getRedevNodealholdtime();// 二次开发未成交时间
				// 获取保留天数
				if (customer.getCustomerType().equals(
						CustomerManage.TWICE_CUSTOMER)) {
					holdTime = redevNodealholdtime + middleServiceCycle;
				} else if (customer.getCustomerType().equals(
						CustomerManage.INTENTION_CUSTOMER)) {
					holdTime = pushNodealholdtime;
				} else {
					holdTime = sysallocationNodealholdtime;
				}
				empCustomRelation.setHoldTime(holdTime);
				empCustomRelation.setIsDebug(ConfigUtil.getString("isTest"));
				empCustomRelationService
						.updateEmpCustomRelation(empCustomRelation);

				// 2、将客户状态历史表中对应的客户状态改为已接收 并且设置接收开始时间&结束时间（流走时间）
				customerStateHistService
						.updateCustomStateByCustomIdAndEmpno(cusIdArray[i],
								empIdArray[i], CustomerManage.ACCEPT_YES);
			}

		}

	}

	/**
	 * 
	 * 方法描述：接收客户(更改)
	 * 
	 * @return
	 * 
	 * 
	 * @author 邢泽江
	 * 
	 *        2016年11月20日17:01:22
	 * @throws 
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/acceptCustom")
	public void acceptCustomer(Customer customer, HttpSession session,
			HttpServletResponse response) throws Exception {
		PrintWriter pw = response.getWriter();

		//1.接收的销售所在部门是否有客户购买的产品销售权
		
//		String customerId = customer.getCusId();
//		String ecrId;
//		String empId;
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}	
//		empId = currentUser.getEmpno();
		//根据customerId确定是否有分配数据
		List<EmpCustomRelation> empCustomRelations = new ArrayList<EmpCustomRelation>();
		empCustomRelations = empCustomRelationService.getEmpCustomRelationByCusId(customer.getCusId());

		if(empCustomRelations==null){
			return;
		}
		EmpCustomRelation empCustomRelation = new EmpCustomRelation();
		empCustomRelation = empCustomRelations.get(0);
		
		// 判断要接收的客户是否还在
		Integer result = checkCustomerIsExist(empCustomRelation.getId(),
				CustomerManage.ACCEPT);
		if (result != 1) {
			pw.println(result);
			return;
		}	

        // 设置状态为接收
		empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
		empCustomRelationService.updateEmpCustomRelation(empCustomRelation);

	
	}
	
	/**
	 * 
	 * 方法描述：回收客户 将公海客户回收有两个操作： 1、将该客户在客户表中对应的记录“客户类型”字段修改为“回收客户”
	 * 2、删除客户销售关系表中的相应记录公海客户记录 3、在客户销售关系表中插入对应的回收记录
	 * 
	 * @param customer
	 *            客户VO
	 * @param session
	 * @param response
	 * 
	 * @author 李丽华[lilihua@xinnet.com] 2014-3-4 下午5:02:39
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/recyclingCustomer")
	public void recyclingCustomer(String ecrIdStr, String customIdStr,
			HttpSession session, HttpServletResponse response) throws Exception {
		PrintWriter pw = response.getWriter();
		Emp emp = (Emp) session.getAttribute("currentUser");
		String[] customIdArray = customIdStr.split(":");
		String[] ecrIdArray = ecrIdStr.split(":");

		for (int i = 0; i < customIdArray.length; i++) {

			// 判断要回收的客户是否还在
			Integer result = checkCustomerIsExist(ecrIdArray[i],
					CustomerManage.RECYCLING);
			if (result != 1) {
				pw.println(result);
				return;
			}

			// 1、将该客户在客户表中对应的记录“客户类型”字段修改为“回收客户”
			Customer customer = new Customer();
			customer.setCustomerType(CustomerManage.RECYCLING_CUSTOMER);
			customer.setCusId(customIdArray[i]);
			customerManageService.modifyCustomerById(customer);

			// 2、删除客户销售关系表中的相应记录公海客户记录
			empCustomRelationService.delByEcrId(ecrIdArray[i]);

			// 3、在客户销售关系表中插入对应的客户销售关系记录
			customer.setPusherId(emp.getEmpno());
			customer.setPusherDeptId(emp.getId());
			customAllotService.allot(customer,
					CustomerManage.RECYCLING_CUSTOMER);

		}
	}

	/**
	 * 
	 * 方法描述： 推送客户时，检验是否达到推送上限，查询出此客户之前都被推送过哪些产品， 并排除已推送过的产品
	 * 
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-1-17 上午10:56:59
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@RequestMapping("/push")
	public void getPushDeptList(String customId, String pushHistoryProductId,
			HttpSession session, HttpServletResponse response) throws Exception {
		PrintWriter pw = response.getWriter();
		// 获取当前登录人的当月推送客户数量
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			pw.println(5);
			return;
		}
		Emp emp=empService.getEmpbyEmpno(currentUser.getEmpno());
//		PushResults pushResults = new PushResults();
//		pushResults.setEmpId(currentUser.getEmpno());
//		List<PushResults> list = customerManageService
//				.getPushNumber(pushResults);
//		int count = 0;
//		if (null != list && list.size() > 0) {
//			count = list.size();
//		}
		// 如果达到推送上限 则不允许推送
		int flag = 0;
		if (emp.getSurplusLimit() == 0) {
			flag = 1;
			pw.println(flag);
			return;
		}
		if (null == customId) {
			flag = 2;
			pw.println(flag);
			return;
		}
		// 获取未推送过的产品
		List<Product> productList = this.customerManageService
				.getNotPushProductByCustomerId(customId);

		// 排除该客户当前负责人所负责的产品
		List<Product> newList = new ArrayList<Product>();
		for (Product p : productList) {
			if (!p.getId().equals(pushHistoryProductId)) {
				newList.add(p);
			}
		}

		String productListStr = null;
		productListStr = mapper.writeValueAsString(newList);
		pw.println(productListStr);

	}

	/**
	 * 
	 * 方法描述：开始推送客户
	 * 
	 * @param customer
	 * @param session
	 * @param response
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-3-4 下午1:40:14
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/doPush")
	public void doPush(Customer customer, HttpSession session,
			HttpServletResponse response) throws Exception {
		Emp emp = (Emp) session.getAttribute("currentUser");
		emp=empService.getEmpbyEmpno(emp.getEmpno());
		if (null == emp) {
			return;
		}
		customer.setPusherId(emp.getEmpno());
		
		customAllotService.allot(customer, CustomerManage.INTENTION_CUSTOMER);
		emp.setSurplusLimit(emp.getSurplusLimit()-1);
		empService.updateSurplusLimit(emp);
		PrintWriter pw = response.getWriter();

		pw.println("推送成功！");

	}

	/**
	 * 
	 * 方法描述：拒绝客户
	 * 
	 * @param cusIdStr
	 *            客户ID集合
	 * @param empIdStr
	 *            销售人员ID集合
	 * @param customer
	 *            存放客户类型
	 * @param response
	 * @throws Exception
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-3-4 下午1:51:17
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/rejectCustomer")
	public void reject(Customer customer, HttpServletResponse response)
			throws Exception {
		String[] ecrIdArray = customer.getEcrIdStr().split(":");
		String[] cusIdArray = customer.getCusIdStr().split(":");
		String[] empIdArray = customer.getEmpIdStr().split(":");

		PrintWriter pw = response.getWriter();
		for (int i = 0; i < ecrIdArray.length; i++) {
			// 判断要拒绝的客户是否还在
			Integer result = checkCustomerIsExist(ecrIdArray[i],
					CustomerManage.REJECT);
			if (result != 1) {
				pw.println(result);
				return;
			}
			// 设置客户销售关系记录ID 在修改该客户在推送历史表中的接收状态为“拒绝”时使用
			customer.setEcrId(ecrIdArray[i]);
			customer.setCusId(cusIdArray[i]);
			customer.setEmpId(empIdArray[i]);

			// 拒绝客户
			customAllotService.allot(customer, CustomerManage.ACCEPT_REJECT);
		}

	}

	/**
	 * 
	 * 方法描述：添加报备客户
	 * 
	 * @param customer
	 *            客户VO
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-2-7 下午2:33:10
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false)
	@RequestMapping("/addReportedCustomer")
	public void addReportedCustomer(Customer customer, HttpSession session,
			HttpServletResponse response) throws Exception {
		PrintWriter pw = response.getWriter();
		// 设置报备人的ID 与 姓名
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		// 查询登录人现有多少报备客户
		Customer param = new Customer();
		param.setEmpno(currentUser.getEmpno());
		param.setCustomerType(CustomerManage.REPORTED_CUSTOMER);
		try {
			/*PageView<Customer> pageView = customerManageService.queryCustomer(
					new PageView<Customer>(), param);
			Integer count = (int) pageView.getRowCount();
			// 如果达到可报备客户上限 则不让报备
			if (null != currentUser.getRepcustomerCount()
					&& count >= currentUser.getRepcustomerCount()) {
				pw.println(0);
				return;
			}*/

			// 删除原来的为未注册新客户
			/*customerManageService.del400Customer(customer.getCusId().trim());*/

			customer.setReportedEmpId(currentUser.getEmpno());
			customer.setReportedEmpName(currentUser.getEname());

			// 开始添加报备客户
			Customer exits = customerManageService.addReportedCustomer(customer);
			if (null != exits) {
				System.out.println(exits.getCusId() + "");
				pw.println(exits.getCusId() + "");
			} else {
				pw.println(1);
			}
		} catch (Exception e) {
			pw.println(3);
		}

	}

	/**
	 * 
	 * 方法描述：删除报备客户
	 * 
	 * @param customerIds
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-2-7 下午4:59:00
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/delReportedCustomer")
	public void delReportedCustomer(String customerIdStr,
			HttpServletResponse response) throws Exception {
		PrintWriter pw = null;
		int flag = 0;

		customerManageService.delCustomerByIds(customerIdStr);

		flag = 1;

		pw = response.getWriter();
		pw.println(flag);

	}

	/**
	 * 
	 * 方法描述：修改报备客户
	 * 
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-2-8 上午9:35:30
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/modifyReportedCustomer")
	public void modifyReportedCustomer(Customer customer,
			HttpServletResponse response) throws Exception {
		PrintWriter pw = null;
		int flag = customerManageService.modifyReportedCustomer(customer);

		pw = response.getWriter();
		pw.println(flag);

	}

	/**
	 * 
	 * 方法描述：查询客户备注
	 * 
	 * @param customerRemark
	 * @param session
	 * @param response
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-2-26 上午11:05:07
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@RequestMapping("/queryCustomerRemark")
	public void queryCustomerRemark(CustomerRemark customerRemark,
			HttpSession session, HttpServletResponse response) throws Exception {
		Emp emp = (Emp) session.getAttribute("currentUser");
		PageView<CustomerRemark> customerRemarks = customerManageService
				.queryCustomerRemark(new PageView<CustomerRemark>(),
						customerRemark, emp);
		
		List<CustomerRemark> customerRemarksList = customerRemarks.getRecords();
		Collections.sort(customerRemarksList,new Comparator<CustomerRemark>() {

			@Override
			public int compare(CustomerRemark o1, CustomerRemark o2) {
				//  按时间进行排序
				return o1.getAddTime().compareTo(o2.getAddTime());
			}
			
		});
		PrintWriter pw = response.getWriter();
		String listStr = mapper.writeValueAsString(customerRemarksList);
		pw.println(listStr);

	}

	/**
	 * 
	 * 方法描述：添加客户备注
	 * 
	 * @param customerRemark
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-2-26 下午1:32:08
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/addCustomerRemark")
	public void addCustomerRemark(CustomerRemark customerRemark,
			HttpSession session, HttpServletResponse response) throws Exception {
		Emp emp = (Emp) session.getAttribute("currentUser");
		if (null == emp) {
			return;
		}
		customerRemark.setId(UUID.randomUUID().toString());
		customerRemark.setEmpId(emp.getEmpno());
		customerManageService.addCustomerRemark(customerRemark);

		PrintWriter pw = response.getWriter();
		pw.println("添加成功！");

	}
	
	/**
	 * 
	 * 方法描述：修改客户备注
	 * 
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-3-5 下午2:01:39
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/modifyCustomerRemark")
	public void modifyCustomerRemark(CustomerRemark customerRemark,
			HttpServletResponse response) throws Exception {
		if (null != customerRemark) {
			customerManageService.modifyCustomerRemarkById(customerRemark);
		}

		PrintWriter pw = response.getWriter();
		pw.println("修改成功！");
	}

	/**
	 * 
	 * 方法描述：页面查询条件 所属人部门组织 所属人的级联
	 * 
	 * 
	 * @author 李丽华[lilihua@xinnet.com]
	 * 
	 *         2014-3-19 上午10:38:32
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@RequestMapping("/checkIsLeaf")
	public void checkIsLeaf(String deptId, HttpServletResponse response)
			throws Exception {
		PrintWriter pw = response.getWriter();
		// 判断此部门之下是否有子部门
		List<Dept> deptList = deptService.getDeptByParentId(deptId);
		List<Emp> empList = null;

		// 如果没有子部门 则获取该部门下的所有销售人员
		if (null == deptList || deptList.size() == 0) {

			empList = customerManageService.getEmpListByDeptId(deptId);

			String listStr = mapper.writeValueAsString(empList);
			pw.println(listStr);
		} else {
			// 如果有子部门 则不进行任何操作
			pw.println(1);
		}

	}

	/**
	 * 接收、拒绝、回收、推送 检查该客户是否还在自己的列表
	 * 
	 * @return type ：操作类型 接收、拒绝、回收、推送
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public int checkCustomerIsExist(String ecrId, Integer type) {
		EmpCustomRelation empCustomRelation = empCustomRelationService
				.getEmpCustomRelationById(ecrId);

		if (null != empCustomRelation) {
			return 1;
		}
		return 0;
	}

	/**
	 * 查询推送详情
	 * 
	 * @param pageView
	 * @param customId
	 * @param response
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@RequestMapping("/queryPushDetails")
	public void queryPushDetails(PageView<CustomStateHist> pageView,
			String customId, HttpServletResponse response) throws Exception {
		PrintWriter pw = response.getWriter();
		pageView = customerStateHistService.getCustomStateHistByCustomId(
				pageView, customId);

		List<CustomStateHist> customStateHistList = null;
		// 获取分页List
		if (null != pageView) {
			customStateHistList = pageView.getRecords();
			// 设置分页参数
			if (null != customStateHistList && customStateHistList.size() > 0) {
				for (CustomStateHist customStateHist : customStateHistList) {
					customStateHist.setPageNow(pageView.getPageNow());
					customStateHist.setPageSize(pageView.getPageSize());
					customStateHist.setRowCount(pageView.getRowCount());
					customStateHist.setPageCount(pageView.getPageCount());
					break ;
				}
			}
		}

		customStateHistList = pageView.getRecords();
		Emp emp = null;
		Product product = null;
		for (CustomStateHist customStateHist : customStateHistList) {
			emp = empService.getEmpbyEmpno(customStateHist.getPusherId());
			product = customerManageService
					.getProductByProductId(customStateHist.getProductId());
			if (null != emp) {
				customStateHist.setPusherName(emp.getEname());
			} else {
				customStateHist.setPusherName("系统");
			}

			// 设置客户类型与产品名称
			customStateHist
					.setCustomerTypeStr(CustomerTypeEnmu
							.getCustomerTypeEnmuByValue(
									customStateHist.getCustomType()).getLabel());
			if (null != product) {
				customStateHist.setProductName(product.getProductName());
			}
		}

		String customerListStr = mapper.writeValueAsString(customStateHistList);
		pw.println(customerListStr);
	}

	/**
	 * 查询相关订单
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@RequestMapping("/queryOrderByCustomId")
	public void queryOrderByCustomId(HttpServletRequest request,PageView<Customer> pageView,
			String customId, HttpServletResponse response) throws Exception {
		PrintWriter pw = response.getWriter();
		Customer customer = new Customer();
		customer.setCustomId(customId);
		Integer rows = Integer.valueOf(request.getParameter("rows"));
		pageView.setPageNow(Integer.valueOf(request.getParameter("page")));
		pageView.setPageSize(rows);
		pageView = orderService.queryOrderByCustomId(pageView, customer);
		Customer serviceTime = null;
		List<Customer> buyGoodsList = pageView.getRecords();
		// 查询服务时间
		for (Customer c : buyGoodsList) {
			String productCode = c.getProductCode();
			if(productCode==null||"".equals(productCode)){
				break;
			}
			if(productCode.substring(0, 1).equals("V")){
				productCode = "V";
			}
			if(productCode.substring(0, 1).equals("D")){
				productCode = "D";
			}
			if(productCode.substring(0, 1).equals("M")){
				productCode = "M";
			}
			if(productCode.indexOf("EC")!=-1){
				productCode = "CHIYUN";
			}
			c.setProductCode(productCode);
			serviceTime = orderService
					.getServiceTimeByServiceIdAndProductCode(c);
			if (null != serviceTime && null != serviceTime.getBuyTime()) {
				c.setBuyTime(serviceTime.getBuyTime());
			}
			if (null != serviceTime && null != serviceTime.getDueTime()) {
				c.setDueTime(serviceTime.getDueTime());
			}
			
			/*c.setPageNow(pageView.getPageNow());
			c.setPageSize(pageView.getPageSize());
			c.setRowCount((int)pageView.getRowCount());
			c.setPageCount((int)pageView.getPageCount());*/
//			c.setRowCount(pageView.getRowCount());
//			c.setPageCount(pageView.getPageCount());
		}
		int totalCount = customer.getRowCount();
		Integer pageCount = (totalCount + rows - 1) / rows;
		pageView.setRowCount(totalCount);
	    pageView.setPageCount(pageCount);
	    pageView.setRecords(buyGoodsList);
		String customerListStr = mapper.writeValueAsString(pageView);
		pw.println(customerListStr);
	}

	/**
	 * 查询购买商品
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@RequestMapping("/queryBuyGoods")
	public void queryBuyGoods(HttpServletRequest request,PageView<Customer> pageView, String customId,
			HttpServletResponse response) throws Exception {
		PrintWriter pw = response.getWriter();
		Customer customer = new Customer();
		customer.setCustomId(customId);
		Integer rows = Integer.valueOf(request.getParameter("rows"));
		pageView.setPageNow(Integer.valueOf(request.getParameter("page")));
		pageView.setPageSize(rows);
		pageView = orderService.queryBuyGoods(pageView, customer);
		Customer serviceTime = null;
		List<Customer> buyGoodsList = pageView.getRecords();
		// 查询服务时间
		for (Customer c : buyGoodsList) {
			if(c.getDueTime() == null||"".equals(c.getDueTime())){
				String productCode = c.getProductCode();
				if(productCode==null||"".equals(productCode)){
					break;
				}
				if(productCode.substring(0, 1).equals("V")){
					productCode = "V";
				}
				if(productCode.substring(0, 1).equals("D")){
					productCode = "D";
				}
				if(productCode.substring(0, 1).equals("M")){
					productCode = "M";
				}
				if(productCode.indexOf("EC")!=-1){
					productCode = "CHIYUN";
				}
				c.setProductCode(productCode);
				serviceTime = orderService
						.getServiceTimeByServiceIdAndProductCode(c);
				if (null != serviceTime && null != serviceTime.getBuyTime()) {
					c.setBuyTime(serviceTime.getBuyTime());
				}
				if (null != serviceTime && null != serviceTime.getDueTime()) {
					c.setDueTime(serviceTime.getDueTime());
				}
			}
			
			/*c.setPageNow(pageView.getPageNow());
			c.setPageSize(pageView.getPageSize());
			c.setRowCount((int)pageView.getRowCount());
			c.setPageCount((int)pageView.getPageCount());*/
//			c.setRowCount(pageView.getRowCount());
//			c.setPageCount(pageView.getPageCount());
		}
		int totalCount = customer.getRowCount();
		Integer pageCount = (totalCount + rows - 1) / rows;
		pageView.setRowCount(totalCount);
	    pageView.setPageCount(pageCount);
	    pageView.setRecords(buyGoodsList);
		String customerListStr = mapper.writeValueAsString(pageView);
		pw.println(customerListStr);
	}

	/**
	 * 查询即将到期商品
	 * 
	 * @param customer
	 * @param page
	 * @param request
	 * @param response
	 * @param session
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryDueSoonGoods")
	public void queryDueSoonGoods(Customer customer, PageView<Customer> page,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}
		// 查询即将到期客户时 传递companyId参数 若角色是总经理 则不传
		String companyId = empService.getCompanyIdFromEmp(currentUser
				.getEmpno());
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());
			customer.setCompanyId(companyId);
		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)
				&& (null == customer.getEmpno() || "".equals(customer
						.getEmpno()))) {
			/*if (null == customer.getDeptId() || "".equals(customer.getDeptId())) {
				customer.setDeptId("");
			}*/

			customer.setDeptId("other");
			customer.setCompanyId(companyId);
			
			Role role = (Role) session.getAttribute("role");
			if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
				customer.setCompanyId(null);
				customer.setDeptId("zjl");
			}
		}

		// 测试的时候 判断是否以Debug模式启动服务 如果是 那么时间查询条件的单位改为分钟
		customer.setIsDebug(ConfigUtil.getString("isTest"));
		PageView<Customer> pageView = customerManageService.queryDueSoonGoods(
				page, customer);
		List<Customer> customerList = null;
		// 获取分页List
		if (null != pageView) {
			customerList = pageView.getRecords();
		}
		
		//判断权限
		Subject subject = SecurityUtils.getSubject();
		if(subject.isPermitted("客户调配") ){
			 map.put("isHasCustomAllot", "0");
		} else {
			map.put("isHasCustomAllot", "1");
		}

		String customerListStr = mapper.writeValueAsString(customerList);
		pw.println(customerListStr);

	}

	/**
	 * 获取未接收的客户数量
	 * 
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@RequestMapping("/getAcceptNoCustomerCountByCustomType")
	public void getAcceptNoCustomerCountByCustomType(Customer customer,
			HttpSession session, HttpServletResponse response) throws Exception {
		PrintWriter pw = response.getWriter();

		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}

		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());
		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)
				&& (null == customer.getEmpno() || "".equals(customer
						.getEmpno()))) {
			// 设置查询的部门
			if (null == customer.getDeptId() || "".equals(customer.getDeptId())) {
				customer.setDeptId(currentUser.getId());
			}

		}

		Integer count = customerManageService
				.getAcceptNoCustomerCountByCustomType(customer);
		pw.println(count);
	}

	/**
	 * 获取即将到期商品数量
	 * 
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@RequestMapping("/getDueSoonGoodsCount")
	public void getDueSoonGoodsCount(HttpSession session,
			HttpServletResponse response) throws Exception {
		/*PrintWriter pw = response.getWriter();

		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}
		Customer customer = new Customer();
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());
		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)
				&& (null == customer.getEmpno() || "".equals(customer
						.getEmpno()))) {
			// 查询即将到期客户时 传递companyId参数 若角色是总经理 则不传
			String companyId = empService.getCompanyIdFromEmp(currentUser
					.getEmpno());
			customer.setCompanyId(companyId);
			Role role = (Role) session.getAttribute("role");
			if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
				customer.setCompanyId(null);
			}
		}
		
		//不管是不是部门负责人 都要传所属部门ID 用于查看权限
		customer.setDeptId(currentUser.getId());
		Integer count = orderService.getDueSoonGoodsCount(customer);

		pw.println(count);*/
		Customer customer = new Customer();
		PrintWriter pw = response.getWriter();
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());
		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)
				&& (null == customer.getEmpno() || "".equals(customer
						.getEmpno()))) {
			if (null == customer.getDeptId() || "".equals(customer.getDeptId())) {
				customer.setDeptId(currentUser.getId());
			}

			// 查询即将到期客户时 传递companyId参数 若角色是总经理 则不传
			String companyId = empService.getCompanyIdFromEmp(currentUser
					.getEmpno());
			customer.setCompanyId(companyId);
			
			Role role = (Role) session.getAttribute("role");
			if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
				customer.setCompanyId(null);
				customer.setDeptId(null);
			}
		}

		// 测试的时候 判断是否以Debug模式启动服务 如果是 那么时间查询条件的单位改为分钟
		customer.setIsDebug(ConfigUtil.getString("isTest"));
		
		pw.print(orderService.getDueSoonGoodsCount(customer));
	}

	/**
	 * 获取即将流走客户数量
	 * 
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@RequestMapping("/getVanishSoonCustomerCount")
	public void getVanishSoonCustomerCount(Customer customer,
			HttpSession session, HttpServletResponse response) throws Exception {
		PrintWriter pw = response.getWriter();

		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}

		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());
		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)
				&& (null == customer.getEmpno() || "".equals(customer
						.getEmpno()))) {
			// 设置查询的部门
			if (null == customer.getDeptId() || "".equals(customer.getDeptId())) {
				customer.setDeptId(currentUser.getId());
			}

		}
		// 获取即将流走客户数量
		Integer count = customerManageService
				.getVanishSoonCustomerCount(customer);
		pw.println(count);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@RequestMapping("/addIntentGood")
	public void addIntentGood(Customer customer,
			HttpSession session, HttpServletResponse response) throws Exception {
		customerManageService.updateCustomerProduct(customer);
		PrintWriter pw = response.getWriter();
		pw.print("ok");
	}
	// 客户基本信息
			
	/**
	 * 获取客户余额
	 * 
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	@RequestMapping("/getCustomerBalance")
	public void getCustomerBalance(HttpSession session,
			HttpServletResponse response,String customId) throws Exception {
		
		PrintWriter pw = response.getWriter();
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}
		Customer customerInfo = memberService.getMemberByCusId(customId);
		pw.print(customerInfo.getBalance());
	}
	
	
	/**
	 * 
	 * 方法描述：查询沟通记录
	 * 
	 * 
	 * 
	 * @author 王志军[wangzhijun@xinnet.com]
	 * 
	 *         2016-1-20 下午14:44:29
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@SuppressWarnings("unchecked")
	@RequestMapping("/customerConsumeList")
	public void queryCustomer(CustomerConsume customerConsume, PageView<CustomerConsume> page,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();

		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}

		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customerConsume.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)) {
			
			customerConsume.setDeptId(currentUser.getId());
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customerConsume.setDeptId(null);
		}

		/*PageView<Customer> pageView = customerManageService.queryCustomer(page,
				customer);*/
		List<CustomerConsume> customerConsumeList = null;
		PageView<CustomerConsume> pageView = customerConsumeManageService.queryCustomerConsume(page, customerConsume);
		
		// 获取分页List
		if (null != pageView) {
			customerConsumeList = pageView.getRecords();
		}
		
		map.put("customerConsume", customerConsume);
		String customerConsumeListStr = mapper.writeValueAsString(customerConsumeList);
		pw.println(customerConsumeListStr);
	}
	
	/**
	 * 
	 * 方法描述：查询工作台新客户
	 * 
	 * 
	 * 
	 * @author xingzejiang
	 * 
	 *         2016年10月18日10:03:22
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/getAllNotAcceptCustom")
	public void getAllNotAcceptCustom(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();

		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}

		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)) {
			
			customer.setDeptId(currentUser.getId());
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}

		//根据角色显示内容  角色表ReceiveCustom字段=1 可接收客户
		if(role.getReceiveCustom()==1){
			customer.setCustomState(0);
		}
		
		List<Customer> customerList = null;
		
		//获取查询结果总条数
		//int rowCount = customerManageService.findAllfitCustomNum(customer);
		int rowCount = 500;
		//根据条件查询数据
		System.out.println("========"+customer.getCustomState()+","+customer.getCustomType()+","+customer.getDeptId());
		customerList = customerManageService.getAllNotAcceptCustom(customer);

		String customerConsumeListStr = mapper.writeValueAsString(customerList);
		//转换成bootstrap-table可以接收的数据结构
		customerConsumeListStr="{\"total\": "+rowCount+",\"rows\":"+customerConsumeListStr+"}";
		pw.println(customerConsumeListStr);
	}
	
	/**
	 * 
	 * 方法描述：查询工作台意向客户
	 * 
	 * 
	 * 
	 * @author xingzejiang
	 * 
	 *         2016年10月19日16:22:41
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/getMindCustom")
	public void getMindCustom(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();

		String search = request.getParameter("search");
		
		customer.setEndAddTime(search);
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}

		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)) {
			
			customer.setDeptId(currentUser.getId());
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}

		List<Customer> customerList = null;
		
		//获取查询结果总条数
		int rowCount = customerManageService.findAllfitCustomNum(customer);
		//根据条件查询数据
		customerList = customerManageService.findAllMindCustom(customer);
		
		String customerConsumeListStr = mapper.writeValueAsString(customerList);
		//转换成bootstrap-table可以接收的数据结构
		customerConsumeListStr="{\"total\": "+rowCount+",\"rows\":"+customerConsumeListStr+"}";
		pw.println(customerConsumeListStr);
	}
	
	/**
	 * 
	 * 方法描述：查询待续费客户
	 * 
	 * 
	 * 
	 * @author xingzejiang
	 * 
	 *         2016年10月20日17:11:56
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/getWaitCharge")
	public void findWaitCharge(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();

		String search = request.getParameter("search");
		
		customer.setEndAddTime(search);
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}

		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)) {
			
			customer.setDeptId(currentUser.getId());
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}

		List<Customer> customerList = null;
		
		//获取查询结果总条数
		int rowCount = customerManageService.findAllfitCustomNum(customer);
		//根据条件查询数据
		customerList = customerManageService.findAllWaitChargeCustom(customer);
		
		String customerConsumeListStr = mapper.writeValueAsString(customerList);
		//转换成bootstrap-table可以接收的数据结构
		customerConsumeListStr="{\"total\": "+rowCount+",\"rows\":"+customerConsumeListStr+"}";
		pw.println(customerConsumeListStr);
	}
	
	/**
	 * 
	 * 方法描述：查询保护期费客户
	 * 
	 * 
	 * 
	 * @author xingzejiang
	 * 
	 *         2016年10月20日17:20:47
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/getProtect")
	public void findProtect(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();

		String search = request.getParameter("search");
		
		customer.setEndAddTime(search);
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}

		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)) {
			
			customer.setDeptId(currentUser.getId());
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}

		List<Customer> customerList = null;
		
		//获取查询结果总条数
		int rowCount = customerManageService.findAllfitCustomNum(customer);
		//根据条件查询数据
		customerList = customerManageService.findAllProtectCustom(customer);
		
		String customerConsumeListStr = mapper.writeValueAsString(customerList);
		//转换成bootstrap-table可以接收的数据结构
		customerConsumeListStr="{\"total\": "+rowCount+",\"rows\":"+customerConsumeListStr+"}";
		pw.println(customerConsumeListStr);
	}
	
	/**
	 * 
	 * 方法描述：查询二次开发费客户
	 * 
	 * 
	 * 
	 * @author xingzejiang
	 * 
	 *         2016年10月20日17:20:47
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/getSecond")
	public void findSecond(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		PrintWriter pw = response.getWriter();
		
		//固定客户类别 二次开发客户 type 2
		customer.setCustomerType(2);

		String search = request.getParameter("search");
		
		customer.setEndAddTime(search);
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}

		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());

		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)) {
			
			customer.setDeptId(currentUser.getId());
		}
		
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}

		List<Customer> customerList = null;
		
		//获取查询结果总条数
		int rowCount = customerManageService.findAllfitCustomNum(customer);
		//根据条件查询数据
		customerList = customerManageService.findAllSecondCustom(customer);
		
		String customerConsumeListStr = mapper.writeValueAsString(customerList);
		//转换成bootstrap-table可以接收的数据结构
		customerConsumeListStr="{\"total\": "+rowCount+",\"rows\":"+customerConsumeListStr+"}";
		pw.println(customerConsumeListStr);
	}
	
	/**
	 * 
	 * 方法描述：查询当前登录账户是否有被分配的未接收客户
	 * 
	 * 
	 * 
	 * @author xingzejiang
	 * 
	 *         2016年10月26日14:42:38
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/judgeUnreceptCustomer")
	public void judgeUnreceptCustomer(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session,Map<String,Object> map) throws Exception {
		
		PrintWriter pw = response.getWriter();
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}
		String flag = "";

		int count = customAllotService.getScanningCountByEmpno(currentUser.getEmpno());
		
		flag=count==0?"false":"true";
		pw.println(flag);
	}
	
	/**
	 * 
	 * 方法描述：接收未接收的客户
	 * 
	 * 
	 * 
	 * @author xingzejiang
	 * 
	 *         2016年11月3日14:53:47
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	@RequestMapping("/receiveCustomer")
	public void receiveCustomer(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session){
		
		// 获取当前登录用户
		Emp currentUser = (Emp) session.getAttribute("currentUser");
		if (null == currentUser) {
			return;
		}	
		
		//判定是否是分配给当前登录用户的客户
		EmpCustomRelation empCustomerRelation = new EmpCustomRelation();
		empCustomerRelation.setEmpId(currentUser.getId());
		EmpCustomRelation empCustomerRelation1 = empCustomRelationService.getEmpCustomRelationByCondition(empCustomerRelation);
		//查询是否有关系表数据，有则更新，没有则新增
		List<EmpCustomRelation> empCustomerRelations = empCustomRelationService.getEmpCustomRelationByCustomId(customer.getCusId());
		if(empCustomerRelations==null||empCustomerRelations.size()==0){
			
		}
	}
	
	private String toString(Object[] a) {
        if (a == null)
            return "null";

        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {
        	b.append("'");
            b.append(String.valueOf(a[i]));
            b.append("'");
            if (i == iMax)
                return b.append(']').toString();
            b.append(", ");
        }
    }
}


